package com.example.musicplayer.activity;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.musicplayer.DataLoadManager;
import com.example.musicplayer.MusicPlayerApplication;
import com.example.musicplayer.MusicStateChangedListener;
import com.example.musicplayer.R;
import com.example.musicplayer.commonUtils.DrawUtil;
import com.example.musicplayer.commonUtils.LanguageUtil;
import com.example.musicplayer.commonUtils.ToastUtil;
import com.example.musicplayer.fragment.dialogFragment.MusicListDialogFragment;
import com.example.musicplayer.musicClass.MusicInfo;
import com.example.musicplayer.musicTools.MusicPlayMode;
import com.example.musicplayer.service.MusicService;
import com.example.musicplayer.service.MusicTabViewService;
import com.example.musicplayer.service.TimedOffService;
import com.example.musicplayer.settings.MusicPlayerSettings;
import com.example.musicplayer.settings.SettingsItem;

//set app language and set music state change listener
public class BaseActivity extends AppCompatActivity implements MusicStateChangedListener
        , MusicTabViewService.CallBackListener {
    private static final String TAG = "BaseActivity";
    //if it should enable MusicStateChangedListener
    private boolean mEnableMusicStateChangedListener = false;
    private boolean mEnableMusicTabView = false;
    private boolean mIsResumed = false;
    private boolean mEnableTimer = false;
    private int mTimerInterval;

    private Handler mHandler;
    private final Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (onRefreshView()) {
                        mHandler.postDelayed(mRunnable, mTimerInterval);
                    }
                }
            });
        }
    };

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(LanguageUtil.loadLanguage(newBase));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mTimerInterval = getResources().getInteger(R.integer.refresh_time);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mIsResumed = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        mIsResumed = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        setEnableTimer(false, false);
        MusicService.MusicBinder binder = getMusicServiceBinder();
        if (binder != null) {
            binder.removeMusicStateChangedListener(this);
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        MusicTabViewService.MusicTabViewBinder binder = getMusicTabViewServiceBinder();
        if (hasFocus && binder != null) {
            if (mEnableMusicTabView) {
                if (binder.isViewAdded()) {
                    binder.shouldMoveView(!(this instanceof MainActivity));
                } else {
                    //set listener, when view is added, move it to the target location, and then remove the listener
                    MusicTabViewService.setMusicTabViewStateListener(isAdded -> {
                        if (isAdded) {
                            binder.shouldMoveView(!(this instanceof MainActivity));
                        }
                        MusicTabViewService.removeMusicTabViewStateListener();
                    });
                }
            }
            showOrHideMusicTabView();
        } else {
            if (mIsResumed && binder != null) {
                binder.shouldShowView(false);
            }
        }
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        updateMusicListDialogFragment();
    }

    protected final boolean isActivityResumed() {
        return mIsResumed;
    }

    protected void setEnableMusicListener(boolean enable) {
        mEnableMusicStateChangedListener = enable;
    }

    protected void setEnableMusicTabView(boolean enable) {
        mEnableMusicTabView = enable;
        showOrHideMusicTabView();
    }

    protected void setEnableTimer(boolean enable, boolean start) {
        mEnableTimer = enable;
        if (enable) {
            if (mHandler == null) {
                mHandler = new Handler();
            }
            if (start) {
                mHandler.post(mRunnable);
            }
        } else {
            if (mHandler != null) {
                mHandler.removeCallbacks(mRunnable);
                mHandler = null;
            }
        }
    }

    protected void setTimerInterval(int timerInterval) {
        if (timerInterval > 0) {
            mTimerInterval = timerInterval;
        }
    }

    protected Handler getHandler() {
        if (mHandler == null) {
            mHandler = new Handler();
        }
        return mHandler;
    }

    protected void post(Runnable action) {
        postDelayed(action, 0);
    }

    protected void postDelayed(Runnable action, long time) {
        if (action != null && time >= 0) {
            getHandler().postDelayed(action, time);
        }
    }

    protected void removeCallbacks(Runnable action) {
        if (action != null) {
            getHandler().removeCallbacks(action);
        }
    }

    public boolean isEnableMusicStateChangedListener() {
        return mEnableMusicStateChangedListener;
    }

    public boolean isEnableMusicTabView() {
        return mEnableMusicTabView;
    }

    public boolean isEnableTimer() {
        return mEnableTimer;
    }

    public final void startTimer() {
        if (mEnableTimer) {
            if (mHandler == null) {
                setEnableTimer(true, true);
            } else {
                mHandler.removeCallbacks(mRunnable);
                mHandler.post(mRunnable);
            }
        }
    }

    public final void pauseTimer() {
        if (mEnableTimer && mHandler != null) {
            mHandler.removeCallbacks(mRunnable);
        }
    }

    public void showOrHideMusicTabView() {
        if (mEnableMusicTabView) {
            MusicTabViewService.setCallBackListener(this);
        } else {
            MusicTabViewService.removeCallBackListener();
        }
        MusicTabViewService.MusicTabViewBinder binder = getMusicTabViewServiceBinder();
        if (binder != null) {
            binder.shouldShowView(mEnableMusicTabView);
        }
    }

    public void updateMusicListDialogFragment() {
        if (mEnableMusicTabView) {
            MusicTabViewService.MusicTabViewBinder binder = getMusicTabViewServiceBinder();
            if (binder != null) {
                binder.updateMusicListView();
            }
        }
    }

    protected void registerMusicListener(MusicService.MusicBinder musicBinder) {
        if (musicBinder != null) {
            musicBinder.addMusicStateChangedListener(this);
        }
    }

    protected MusicService.MusicBinder getMusicServiceBinder() {
        Binder binder = MusicPlayerApplication.getInstance().getMusicServiceBinder();
        if (binder != null) {
            return (MusicService.MusicBinder) binder;
        }
        return null;
    }

    protected MusicTabViewService.MusicTabViewBinder getMusicTabViewServiceBinder() {
        Binder binder = MusicPlayerApplication.getInstance().getMusicTabViewServiceBinder();
        if (binder != null) {
            return (MusicTabViewService.MusicTabViewBinder) binder;
        }
        return null;
    }

    public void setPendingTransition(int enterAnim, int exitAnim) {
        if (!MusicPlayerSettings.isAnimEffect()) {
            enterAnim = 0;
            exitAnim = 0;
        }
        overridePendingTransition(enterAnim, exitAnim);
    }

    public void notExitTemporarily() {
        DataLoadManager dataLoadManager = DataLoadManager.getInstance();
        if (dataLoadManager != null) {
            dataLoadManager.writeOneBaseData(DataLoadManager.TIME_TO_EXIT_ON, false);
            dataLoadManager.writeOneBaseData(DataLoadManager.TIMING_SET, SettingsItem.TimedOffItem.TIMING_DEFAULT);
        }
        //stop timed off service
        TimedOffService.stopTimedOffService();
    }

    protected boolean onRefreshView() {
        return true;
    }

    protected void onMusicCompletion(MusicInfo musicInfo) {
    }

    protected void onMusicPrepared(MusicInfo musicInfo) {
    }

    protected void onMusicEmpty(MusicInfo musicInfo) {
    }

    protected void onMusicFavoriteChanged(MusicInfo musicInfo, boolean result) {
    }

    protected void onMusicPlayStateChanged(MusicInfo musicInfo, boolean isPlaying) {
    }

    protected void onMusicPlayModeChanged(MusicInfo musicInfo, MusicPlayMode mode) {

    }

    protected void onPlayNext(MusicInfo beforeMusic, MusicInfo afterMusic) {
    }

    protected void onPlayLast(MusicInfo beforeMusic, MusicInfo afterMusic) {
    }

    @Override
    public void musicCompletion(MusicInfo musicInfo) {
        if (mEnableMusicStateChangedListener) {
            onMusicCompletion(musicInfo);
        }
    }

    @Override
    public void musicPrepared(MusicInfo musicInfo) {
        if (mEnableMusicStateChangedListener) {
            onMusicPrepared(musicInfo);
        }
        updateMusicListDialogFragment();
    }

    @Override
    public void musicEmpty(MusicInfo musicInfo) {
        if (mEnableMusicStateChangedListener) {
            onMusicEmpty(musicInfo);
        }
    }

    @Override
    public void musicFavoriteChanged(MusicInfo musicInfo, boolean result) {
        if (mEnableMusicStateChangedListener) {
            onMusicFavoriteChanged(musicInfo, result);
        }
    }

    @Override
    public void musicPlayStateChanged(MusicInfo musicInfo, boolean isPlaying) {
        if (mEnableMusicStateChangedListener) {
            onMusicPlayStateChanged(musicInfo, isPlaying);
        }
    }

    @Override
    public void musicPlayModeChanged(MusicInfo musicInfo, MusicPlayMode mode) {
        if (mEnableMusicStateChangedListener) {
            onMusicPlayModeChanged(musicInfo, mode);
        }
    }

    @Override
    public void musicPlayNext(MusicInfo beforeMusic, MusicInfo afterMusic) {
        if (mEnableMusicStateChangedListener) {
            onPlayNext(beforeMusic, afterMusic);
        }
    }

    @Override
    public void musicPlayLast(MusicInfo beforeMusic, MusicInfo afterMusic) {
        if (mEnableMusicStateChangedListener) {
            onPlayLast(beforeMusic, afterMusic);
        }
    }

    @Override
    public void showMusicList(MusicListDialogFragment musicListDialogFragment) {
        if (musicListDialogFragment != null) {
            musicListDialogFragment.show(getSupportFragmentManager(), "musicListDialog");
        }
    }

    @Override
    public void jumpToMusicPlayActivity() {
        if (mEnableMusicTabView) {
            MusicPlayerApplication.getInstance().setScreenShot(DrawUtil.getScreenShot(this));
            Intent intent = new Intent(this, MusicPlayActivity.class);
            this.startActivity(intent);
            setPendingTransition(R.anim.music_play_activity_enter, R.anim.fake_anim);
        } else {
            ToastUtil.makeToast(getString(R.string.jump_to_music_play_activity_error));
        }
    }

    public void jumpToMusicDetailsActivity() {
        if (getMusicServiceBinder() != null) {
            Intent intent = new Intent(this, MusicDetailsActivity.class);
            int musicId = getMusicServiceBinder().getId();
            if (musicId >= 0) {
                intent.putExtra("musicId", getMusicServiceBinder().getId());
                this.startActivity(intent);
                setPendingTransition(R.anim.normal_left_enter, R.anim.normal_left_exit);
            }
        } else {
            ToastUtil.makeToast(getString(R.string.jump_to_music_play_activity_error));
        }
    }
}